#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: serializer.py
@contact: zwb15083976291@163.com
@time: 2021/11/10
"""
from collections import OrderedDict

from django.db.models import Q
from common.models import BlogTag, BlogTagArticle
from rest_framework import serializers
from utils.serializers.serializer import SpecifySerializeFieldSerializer, SpecifySerializeFieldModelSerializer, \
    UpdateBaseSerializeMethodMixin


class TagSerializer(UpdateBaseSerializeMethodMixin, SpecifySerializeFieldModelSerializer):
    id = serializers.IntegerField()

    class Meta:
        model = BlogTag
        fields = '__all__'


class PostTagSerializer(TagSerializer):

    def validate_tag_name(self, value):
        if BlogTag.objects.filter(tag_name=value).first():
            raise serializers.ValidationError("标签已存在")

        return value


class DeleteTagSerializer(TagSerializer):

    def validate_id(self, value):
        tag = BlogTag.objects.filter(id=value).first()
        if not tag:
            raise serializers.ValidationError('标签不存在')
        if tag.articles_count != 0 or BlogTagArticle.objects.filter(tag_id=value).count() != 0:
            raise serializers.ValidationError("删除失败,存在文章相关联")
        self.context["tag_obj"] = tag
        return value


class PutTagSerializer(TagSerializer):
    def validate_tag_name(self, value):
        if BlogTag.objects.filter(tag_name=value).first():
            raise serializers.ValidationError("标签名已存在")
        return value

    def validate_id(self, value):
        tag = BlogTag.objects.filter(id=value).first()
        if not tag:
            raise serializers.ValidationError('标签不存在')
        self.context["tag_obj"] = tag
        return value


class BatchDeleteTagSerializer(SpecifySerializeFieldSerializer):
    ids = serializers.ListField(label="文章id")

    def validate_ids(self, value):
        query_set = BlogTag.objects.filter(Q(id__in=set(value)))
        result = set(value) - set(query_set.values_list('id', flat=True))
        if result:
            raise serializers.ValidationError(f"删除失败!,{result} 不存在")

        query_set = BlogTag.objects.filter(Q(id__in=set(value)) & Q(articles_count=0))
        result = set(value) - set(query_set.values_list('id', flat=True))
        if result:
            raise serializers.ValidationError(f"删除失败!,{result}存在文章相关联")
        return value
